#!/bin/sh
#
# Start/stop oVirt Engine
#
# chkconfig: - 65 34
# description: oVirt Engine
# pidfile: /var/run/ovirt-engine.pid

### BEGIN INIT INFO
# Provides: ovirt-engine
# Short-Description: oVirt Engine
### END INIT INFO

# Source function library.
. /etc/rc.d/init.d/functions

NAME="ovirt-engine"
PROG="oVirt Engine"

[ -f "/etc/sysconfig/${NAME}" ] && . "/etc/sysconfig/${NAME}"

RETVAL=0
LOCKFILE="/var/lock/subsys/${NAME}"
PIDFILE="${PIDFILE:-/var/run/${NAME}.pid}"
USER="@ENGINE_USER@"
ENGINE_USR="@ENGINE_USR@"

# See how we were called.
case "$1" in
	start)
		if [ `id -u` -ne 0 ]; then
			echo $"Insufficient privilege" 1>&2
			exit 4
		fi
		printf $"Starting $PROG: "
		ulimit -n ${FILENO:-65535}
		touch "${PIDFILE}"
		chown "${USER}" "${PIDFILE}"
		daemon --user "${USER}" --pidfile="${PIDFILE}" \
			"${ENGINE_USR}/services/${NAME}/${NAME}.py" \
				--pidfile="${PIDFILE}" \
				--background \
				--redirect-output \
				${EXTRA_ARGS} \
				start
		RETVAL=$?
		echo
		if [ $RETVAL -eq 0 ]; then
			touch "${LOCKFILE}"
		else
			if [ -f "${LOCKFILE}" ]; then
				RETVAL=0
			fi
		fi
		while :
		do
			if HTTP_STATUS=$(curl -kIs 'https://localhost/ovirt-engine/services/host-register?version=1&command=get-pki-trust') ; then
				HTTP_STATUS_CODE=$(echo ${HTTP_STATUS} | head -1 | cut -d ' ' -f 2)
				if [ "${HTTP_STATUS_CODE}" == '200' ]; then
					break
				fi
			fi
			sleep 1
		done
		[ $RETVAL -ne 0 -a ! -s "${PIDFILE}" ] && rm -f "${PIDFILE}"
		;;
	stop)
		printf $"Stopping $PROG: "
		killproc -p "${PIDFILE}" -d 60
		RETVAL=$?
		echo
		[ $RETVAL -eq 0 ] && rm -f "${LOCKFILE}"
		;;
	status)
		status -p "${PIDFILE}" "${NAME}"
		RETVAL=$?
		;;
	restart)
		$0 stop
		$0 start
		RETVAL=$?
		;;
	*)
		echo $"Usage: $0 {start|stop|status|restart}"
		exit 2
		;;
esac

exit $RETVAL
